package com.dk.shared.autoconfigure.dbaccess;

import com.dk.common.dbaccess.commont.HibernateProperties;
import com.dk.common.dbaccess.listener.AuditingEntityListener;
import com.dk.common.dbaccess.listener.AuditingHandler;
import com.dk.common.dbaccess.repository.DBAccessRepositoryImpl;
import com.dk.common.defs.CommonDefs;
import com.dk.shared.defs.SharedDefs;
import com.dk.shared.utils.UserAuditorAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.domain.AuditorAware;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.mapping.context.MappingContext;

@Configuration
@EnableJpaAuditing
@EntityScan(CommonDefs.TOP_PACKAGE_BASE)
@EnableJpaRepositories(value = CommonDefs.TOP_PACKAGE_BASE,
        repositoryBaseClass = DBAccessRepositoryImpl.class)
public class DBAccessAutoConfiguration {
    //FROM org.springframework.data.jpa.repository.config.BeanDefinitionNames.JPA_MAPPING_CONTEXT_BEAN_NAME
    private static final String JPA_MAPPING_CONTEXT_BEAN_NAME = "jpaMappingContext";
    @Lazy
    @Autowired
    @Qualifier(JPA_MAPPING_CONTEXT_BEAN_NAME)
    private MappingContext mappingContext;



    @ConditionalOnClass(AuditorAware.class)
    @Bean(SharedDefs.AUDITOR_AWARE_BEAN_NAME)
    @ConditionalOnMissingBean(name = SharedDefs.AUDITOR_AWARE_BEAN_NAME)
    public UserAuditorAware userAuditorAware() {
        UserAuditorAware userAuditorAware = new UserAuditorAware();

        AuditingEntityListener.setHandler(new AuditingHandler(mappingContext, userAuditorAware));

        return userAuditorAware;
    }

    @Bean
    public HibernateProperties hibernateProperties() {
        return new HibernateProperties();
    }
}
